package com.zrx.app.android.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zrx.app.android.R;
import com.zrx.app.android.UTIL.RemoteConn;
import com.zrx.app.android.fragment.FragmentShowbackReason;
import com.zrx.app.android.modules.BaseModule_two;

import java.util.Collections;
import java.util.Comparator;
import java.util.concurrent.ExecutionException;

/**
 * Created by $HL on 2017/9/23.
 */

public class ListContentActivity_two extends BaseActivity {
    private static final String TAG = "ListContentActivity_two";
    TextView label_state;
    EditText text_search_key;
    Button btn_search,btn_reset,btn_fetch_more;
    AbsListView list_view;
    BaseModule_two module;
    ListContentActivity_two.MyAdapter_Two adapter;

    private int totalPageNum;
    private int pageNum;
    private int pageSize=20;

    JSONArray arr1;
    int totalPageNum1;

    int pageNum1;
    String backReason = null;



    private String moduleName;


    int getOrder(String state){
        switch (state) {
            case "UPLOADING":
                return 30;
            case "EXAM_SENDBACK":
                return 20;
            case "CREDIT_AUDIT_PASS":
                return 50;
            case "TARCUSTOM":
                return 40;
            default:
                return 100;
        }
    }

    Comparator<Object> stateSort = new Comparator<Object>() {
        @Override
        public int compare(Object a, Object b) {
            if(a==b || a.equals(b))
                return 0;

            String aState=((JSONObject) a).getString("state");
            String bState=((JSONObject) b).getString("state");
            int aOrder=getOrder(aState);
            int bOrder=getOrder(bState);
            if(a!=b)
                return aOrder-bOrder;
            else{
                long aModified=((JSONObject) a).getLong("modifiedDate");
                long bModified=((JSONObject) b).getLong("modifiedDate");
                return (int)(bModified-aModified);
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_content_two);
        label_state= (TextView) findViewById(R.id.label_state);
        text_search_key= (EditText) findViewById(R.id.text_search_key);
        btn_search= (Button) findViewById(R.id.btn_search);
        btn_reset= (Button) findViewById(R.id.btn_reset);
        btn_fetch_more= (Button) findViewById(R.id.btn_fetch_more);
        list_view= (AbsListView) findViewById(R.id.list_view);

        final ListContentActivity_two self = this;
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//搜索按钮                AsyncTask异步处理
                  pageNum = 0;
                new ListContentActivity_two.FetchDataTask(self).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageSize, pageNum, text_search_key.getText().toString());
            }
        });

        btn_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//重置按钮
                text_search_key.setText("");
                pageNum=0;
                new ListContentActivity_two.FetchDataTask(self).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,pageSize,pageNum,text_search_key.getText().toString());
            }
        });
        btn_fetch_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//下载更多按钮
                pageNum++;
                new ListContentActivity_two.FetchDataTask(self).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,pageSize,pageNum,text_search_key.getText().toString());
            }
        });

        //mainURL=getIntent().getStringExtra("mainURL");

        module= (BaseModule_two) getIntent().getSerializableExtra("module");    //获取到module对象
        moduleName=module.getModuleName();

        adapter=new ListContentActivity_two.MyAdapter_Two();
        list_view.setAdapter(adapter);

     /*list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    JSONObject reason = arr1.getJSONObject(position);
                    JSONObject basicData = null;
                    if (reason.containsKey("basicData"))
                        basicData = reason.getJSONObject("basicData");
                    if (basicData != null) {
                        if (basicData.containsKey("退回原因"))
                            backReason = basicData.getString("申请人");
                        else backReason = "1.这里是返回原因";
                        Log.e(TAG, backReason);
                    }
                }catch (Exception e){
                    Log.e(TAG,e.getMessage());
                }

                    FragmentShowbackReason editNameDialog = new FragmentShowbackReason(backReason);
                    editNameDialog.show(getFragmentManager(), "FragmentShowbackReason");

            }
        });*/
          /* list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
               @Override
               public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                   FragmentShowbackReason editNameDialog = new FragmentShowbackReason();
                   editNameDialog.show(getFragmentManager(), "FragmentShowbackReason");
               }
           });*/
    }

    @Override
    public void onResume() {   //重新开始
        super.onResume();
        pageNum=0;
        new ListContentActivity_two.FetchDataTask(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,pageSize, pageNum,text_search_key.getText().toString());
    }

    @Override
    protected String getModuleName() {
        return moduleName;
    }

    public static void startActivity(Context context, BaseModule_two module) {
        try {
            Intent intent = new Intent(context,ListContentActivity_two.class);
            intent.putExtra("module",module);
            context.startActivity(intent);
        }catch (Exception e){
            Log.e(TAG,"产生异常");
        }
    }


    class FetchDataTask extends AsyncTask {

        Context context;

        public FetchDataTask(Context context) {
            this.context = context;
        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            label_state.setText("正在加载数据");
        }

        @Override
        protected Object doInBackground(Object[] params) {     //后台操作结束后自动进行
            RemoteConn http = RemoteConn.getInstance();
            int size= (int) params[0];
            int page= (int) params[1];
            String searchKey= (String) params[2];
            return http.fetchData2(module.getMainURL(),searchKey,size,page);    //获取数据传到onPostExecute里面
        }

        @Override
        protected void onPostExecute(Object o) {   //这个方法在doinbackground后面执行
            super.onPostExecute(o);
            if (o != null && o instanceof JSONObject) {
                try {
                    JSONArray arr = ((JSONObject) o).getJSONArray("content");
                    totalPageNum = ((JSONObject) o).getIntValue("totalPages");
                    pageNum = ((JSONObject) o).getIntValue("number");

                 /*   JSONArray arr1 = ((JSONObject) o).getJSONArray("content");
                    totalPageNum1 = ((JSONObject) o).getIntValue("totalPages");
                    pageNum1 = ((JSONObject) o).getIntValue("number");*/

                    if (pageNum == 0)
                        adapter.setData(arr);
                    else
                    {adapter.addData(arr);}//传入adapter
                    Collections.sort(adapter.getData(), stateSort);
                    adapter.notifyDataSetChanged();
                    //配置适配器
                    label_state.setText("已从服务器加载数据");
                } catch (Exception e) {
                    Log.d(TAG,e.getMessage());
                    label_state.setText("从服务器加载出错，请重试");
                }finally {
                    //mSwipeLayout.setRefreshing(false);
                }

            } else {
                label_state.setText("从服务器加载失败");
            }
        }
    }

      /* @Override
        protected void onPostExecute(Object o) {   //这个方法在doinbackground后面执行
            super.onPostExecute(o);
            if (o != null && o instanceof JSONObject) {
                try {
                    String value = "[{\"申请人\":\"张三\",\"身份证号\":\"339005111105555500\",\"手机号\":\"15899999888\",\"state\":\"0\",\"useTime\":\"121\",\"backReason\":\"qq\"}]";
                    JSONArray arr = (JSONArray) JSON.parse(value);
                        adapter.addData(arr);
                      //  adapter.addData(arr);   //传入adapter
                    Collections.sort(adapter.getData(), stateSort);
                    adapter.notifyDataSetChanged();
                    //配置适配器
                    label_state.setText("已从服务器加载数据");

                } catch (Exception e) {
                    Log.d(TAG,e.getMessage());
                    label_state.setText("从服务器加载出错，请重试");
                }finally {
                    //mSwipeLayout.setRefreshing(false);
                }

            } else {
                label_state.setText("从服务器加载失败");
            }
        }
    }*/


    class MyAdapter_Two extends BaseAdapter {
        JSONArray data=new JSONArray();

        public JSONArray getData(){
            return data;
        }

        public int getCount() {
            return data.size();
        }

        public Object getItem(int item) {
            return item;
        }

        public long getItemId(int id) {
            return id;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            JSONObject record=data.getJSONObject(position);
            return module.getView(record,parent);    //这里用来获取Basemodule的页面
        }
        public void setData(JSONArray data) {
            this.data = data;
        }

        public void addData(JSONArray arr) {
            data.addAll(arr);

        }

        public boolean hasData() {
            return data != null;
        }
    }

}
